<?php
/**
 * Category AND Tag deal
 * @author fanyee
 *
 */
class CategoryController extends Controller
{
	public function  actionCate()
	{
		$this->channel = 'web_manager_cate';
		$data = array();
		$model=new Category('search');
		$cateForm = new Category();
		if(isset($_POST['Category'])){
			$tagForm =$this->storeTag($_POST['Category'],$cateForm);
		}
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Category']))
			$model->attributes=$_GET['Category'];
		
		$data ['model'] = $model;
		$data ['cateForm'] = $cateForm;
		$this->render('cate',$data);
	}
	
	public function actionTag()
	{
		$this->channel = 'web_manager_tag';
		$data = array();
		$model=new Tag('search');
		$tagForm = new Tag();
		if(isset($_POST['Tag'])){
			$tagForm =$this->storeTag($_POST['Tag'],$tagForm);
		}
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Tag']))
			$model->attributes=$_GET['Tag'];
		
		$data ['model'] = $model;
		$data ['tagForm'] = $tagForm;
		$this->render('tag',$data);
	}
	/**
	 * 删除
	 * @var intenger id
	 * @throws CHttpException
	 */
	public function actionDelete($id,$type)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id,$type)->delete();
			if($type=='Category'){
				Tag::model()->deleteAllByAttributes(array('category_id'=>$id)); 
			}
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	/**
	 * 存储Tag
	 * @param Array $data
	 * @param CActiveRecord $tag
	 */
	private function storeTag($data,CActiveRecord $tag){
		$tag->attributes = $data;
		if($tag->save()){
			Yii::app()->user->setFlash('success','添加标签成功');
			$this->refresh();
		}
		else
			return $tag;
	}
}